﻿#region License
// (c) Garry McGlennon 2009
// 
// This project is made available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// 
// View the project and the latest code at http://dnpframework.codeplex.com/
// 
// All other rights reserved.
// 
// blog: www.dotNetProfessional.com/blog/
#endregion
#region Using Statements

using dnp.Framework.Database.InformationSchema;

#endregion

namespace dnp.Framework.Database.DatabaseExplorer
{
    /// <summary>
    /// A representation of either a stored procedure or function
    /// Only functions currently support column names.
    /// </summary>
    public class Routine : SchemaBase
    {
        private RoutineColumnCollection _columns = new RoutineColumnCollection();
        private RoutineParameterColumnCollection _parameters = new RoutineParameterColumnCollection();
        private readonly string _schema;

        public Routine(Database parent, RoutineParameterColumnSchemaCollection parameters)
            : base(parameters[0].TableName, parent, parent)
        {

            // Populate base class
            _schema = parameters[0].TableSchema;

            this.PopulateParameters(parameters);
        }

        public Routine(Database parent, ColumnSchemaCollection columns)
            : base(columns[0].TableName, parent, parent)
        {

            // Populate base class
            _schema = columns[0].TableSchema;

            this.PopulateColumns(columns);
        }

        private void PopulateParameters(RoutineParameterColumnSchemaCollection parameters)
        {
            _parameters = new RoutineParameterColumnCollection(this, parameters);
        }

        internal void PopulateColumns(ColumnSchemaCollection columns)
        {
            _columns = new RoutineColumnCollection(this, columns);
        }

        public new Database Parent
        {
            get { return base.Parent as Database; }
        }

        public string Schema
        {
            get { return _schema; }
        }

        public RoutineColumnCollection Columns
        {
            get { return _columns; }
        }

        public RoutineParameterColumnCollection Parameters
        {
            get { return _parameters; }
        }

        public override string FullName
        {
            get { return this.Schema + "." + this.Name; }
        }

        public string SafeFullName
        {
            get { return string.Format("[{0}].[{1}]", this.Schema, this.Name); }
        }

        public string Text
        {
            get { return this.Parent.Provider.RetrieveText(this); }
        }
    }
}